import React, {Component} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import {
  Row,
  Col,
  Card,
  Form,
  Menu,
  Input,
  Icon,
  Dropdown,
  Popover,
  InputNumber,
  DatePicker,
  message,
  Badge,
  Divider,
  Upload,
  Collapse, Empty,Select, Button, Table, Modal
} from 'antd';
import CreateModal from './CreateModal'
const Option = Select.Option;

const {MonthPicker, RangePicker} = DatePicker;
@connect(({carousel_image, loading}) => ({
  carousel_image,
  loading: loading.models.carousel_image,
}))
@Form.create()
export default class carousel_image extends Component {
  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'carousel_image/fetch',
      payload:{
        "page_num": 1,
        "page_size": 10
      },
    });
  }
  tableChange = (pagination, filters, sorter) => {
    const params = {
      page_num: pagination.current,
      page_size: pagination.pageSize,
    };
    this.searchList(params);
  }
  searchList = (pagination)=>{
    const { carousel_image: {
      pagination :{
        page_num,
        page_size
      }
    },dispatch} = this.props;
    const pageInfo = pagination?pagination:{page_num,page_size}
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const valuesEnd = {
          ...pageInfo,
          ...values
        };
        /*if (values.role_name) {
          valuesEnd.role_name = values.role_name;
        }
        if (values.create_time && values.create_time.length > 0) {
          valuesEnd.created_time_from = moment(values.create_time[0]).format('YYYY-MM-DD HH:mm:ss');
          valuesEnd.created_time_to = moment(values.create_time[1]).format('YYYY-MM-DD HH:mm:ss');
        }*/
        const action = {
          type: `carousel_image/fetch`,
          payload: valuesEnd,
        };
        dispatch(action);
      }
    });
  }
  onPreview=(record)=>{
    if (record && record.type ==='image') {
      window.open(record.preview);
    }else if (record && record.type ==='video') {
      window.open(record.play_url);
    }

  }
  createOnSubmit=(parms,callback)=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'carousel_image/create',
      payload :{
        ...parms
      }
    }).then((r)=>{
      console.log(r);
      callback();
      if (r){
        message.success('操作成功');
        this.searchList({'page_size': 10,'page_num': 1,})
        this.saveState({createModalVisible:false})
      }
    });
  }
  showModal =(modal_type)=>{
    const { carousel_image: {
    },dispatch} = this.props;
    switch (modal_type){
      case 'create' :
        dispatch({
          type: 'carousel_image/showCreateModal',
        });
        break;
    }
  }
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const { page_type_list} =this.props.carousel_image
    return (
      <Form onSubmit={(e)=>{
        e.preventDefault();
        this.searchList({'page_size': 10,'page_num': 1,})
      }} layout="inline">
        <div
          style={{
            fontSize: '16px',
            marginBottom: '15px',
          }}
        >
          <div style={{ height: 60 }}>
            <Row align="middle">
              <Col xl={12} lg={12} sm={24} align="left" style={{ marginTop: 13 }}>
                <div style={{
                  marginTop: '2px',
                  marginRight: '4px',
                  display: 'inline-block',
                }}>幻灯片应用位置 :
                </div>
                {getFieldDecorator('position')(
                  <Select allowClear  placeholder="请选择"  style={{ width: '65%' }}>
                    {
                      page_type_list.map((item)=>{
                        return  (
                          <Option key={item.value} value={item.value}>
                            {item.name}
                          </Option>
                        )
                      })
                    }
                  </Select>
                )}
              </Col>
            </Row>
          </div>
          <Row gutter={30}>
            <Col md={18} sm={24} align="left" style={{ paddingLeft: 10 }}>
              <span>
                  <Button type="primary" onClick={()=>this.showModal('create')}>
                    新建
                  </Button>
                </span>
            </Col>
            <Col md={6} sm={24} align="right" style={{ paddingLeft: 10 }}>
               <span>
                  <Button type="primary" htmlType="submit">查询</Button>
                  <Button style={{ marginLeft: 8 }} onClick={()=>{this.props.form.resetFields()}}>重置</Button>
               </span>
            </Col>
          </Row>
        </div>
      </Form>
    )

  }

  saveState=(parms)=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'carousel_image/save',
      payload: {
        ...parms
      },
    });
  }
  deleteCarousel =(id)=>{
    const { carousel_image: {
    },dispatch} = this.props;
    const _this  = this;
    Modal.confirm({
      okText: "确定",
      cancelText: "取消",
      title: '确认删除吗',
      content: '您确定要删除这条数据吗？',
      onOk() {
        dispatch({
          type: 'carousel_image/deleteById',
          payload :{
            carousel_image_id:id
          }
        }).then((r)=>{
          console.log(r);
          if (r){
            message.success('操作成功');
            _this.searchList()
          }
        });
      }
    })

  }
  handleMenuClick = ({key},data)=>{
    //console.log(key,data);
    switch (key){

      case 'delete' :
        this.deleteCarousel(data.carousel_image_id)
        break;

    }
  }
  render() {

    const  {carousel_image:{list,pagination ,page_map,createModalVisible,page_type_list},loading}= this.props;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total) =>
        `共有 ${parseInt(total)} 条数据 当前第${pagination.page_num}页`,
      ...pagination,
    };
    const columns=[
      {
        title: '缩略图',
        align: 'center',
        dataIndex: 'preview',
        render: (text, record) => {
          return <img key={record.preview} onClick={() => this.onPreview(record)}  src={record.preview}  style={{height: '60px',width: '100px'}}/>
        }
      },
      {
        title: '轮播图所属页面',
        align: 'center',
         dataIndex: 'position',
        render: (text, record) => {
          return page_map[record.position]
        }
      },
      {
        title: '轮播图类型',
        align: 'center',
        dataIndex: 'type',
        render: (text, record) => {
          return record.type === 'image'? '图片':'视频'
        }
      },
      {
        title: '操作',
        fixed: 'right',
        width: 250,
        render: (text, record) => {
          const menu = (
            <Menu onClick={(key)=>this.handleMenuClick(key,record)}>
              <Menu.Item key="delete">
                <Icon type="delete" />
                删除
              </Menu.Item>
            </Menu>
          );
          return (
            <Dropdown overlay={menu}>
              <Button>
                操作<Icon type="down" />
              </Button>
            </Dropdown>
          )
        },
        align: 'center',
      },
    ]
    return (
      <PageHeaderWrapper loading={loading}>
        <div
          style={{
            backgroundColor: '#FFFFFF',
            paddingLeft: '5%',
            paddingRight: '5%',
          }}
        >
          {this.renderSimpleForm()}
          <Table
            dataSource={list}
            columns={columns}
            rowKey={record => record.carousel_image_id}
            onChange={this.tableChange}
            pagination={paginationProps}
          />
          <CreateModal
            createModalVisible={createModalVisible}
            clseModal = {()=>{this.saveState({createModalVisible:false})}}
            page_type_list={page_type_list}
            createOnSubmit={this.createOnSubmit}
          />

        </div>
      </PageHeaderWrapper>
    );
  }
}
